<template>
<!-- 居中 -->
<span style="font-size: 24px; font-weight:250; margin-bottom: 10px; display: flex; justify-content: center; align-items: center">销售合同</span>

<el-form :model="form" label-width="auto" style="justify-content: center; align-items: center">
    <table>
        <table   style="width: 100%">
            <tr>
            <td colspan="4" style="text-align:left">
                <span >基本信息</span>
            </td>
        </tr>
        <tr>
            <td>
                <el-form-item label="客户名称">
      <el-input v-model="form.addDtos.clientName"  @dblclick="dialogVisible3 = true"  placeholder="双击选择客户名称" />
      

    </el-form-item>
            </td>
            <td>
                <el-form-item label="签约日期">
       <el-date-picker
        v-model="form.addDtos.scAgencyDate"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
                 </el-form-item>
            </td>
            <td>
      <el-form-item label="合同主题">
      <el-input v-model="form.addDtos.contractTopic" />
    </el-form-item>
            </td>
            <td>
      <el-form-item label="合同编号">
      <el-input v-model="form.addDtos.sCcontractNumber" disabled />
    </el-form-item>
            </td>
        </tr>
        <tr>
            <td>
                <el-form-item label="起始日期">
       <el-date-picker
        v-model="form.addDtos.scStartDate"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
                 </el-form-item>
            </td>
            <td>
                <el-form-item label="截至日期">
       <el-date-picker
        v-model="form.addDtos.scEndDate"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
                 </el-form-item>
            </td>
            <td>
      <el-form-item label="我方代表">
      <el-input v-model="form.addDtos.scPeople"  @dblclick="dialogVisible1 = true" placeholder="双击选择我方代表" />
    </el-form-item>
            </td>
            <td>
      <el-form-item label="对方代表">
      <el-input v-model="form.addDtos.scCountpartPeople"  @dblclick="dialogVisible2 = true" placeholder="双击选择对方代表"  />
    </el-form-item>
            </td>
        </tr>
        <tr>
            <td>
    <el-form-item label="合同类别">
      <el-select v-model="form.addDtos.scContractType" placeholder="请选择">
        <el-option label="产品订单" value="产品订单" />
        <el-option label="经销合同" value="经销合同" />
        <el-option label="代销合同" value="代销合同" />
        <el-option label="承包合同" value="承包合同" />
        <el-option label="联销合同" value="联销合同" />
      </el-select>
    </el-form-item>
            </td>
            <!-- <td>
      <el-form-item label="销售人员">
      <el-input v-model="form.addDtos.scSalespeople" />
    </el-form-item>
            </td>  -->
                <td>
      <el-form-item label="制表人员">
      <el-input v-model="form.addDtos.documentMakers" />
    </el-form-item>
            </td> 
            <td>
                <el-form-item label="制单日期">
       <el-date-picker
        v-model="form.addDtos.documentTime"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
                 </el-form-item>
            </td>
        </tr>
        </table>
        <table   style="width: 100%" > 
        <tr>
            <td colspan="4" style="text-align:left">
                <span >金额信息</span>
            </td>
        </tr>
        <tr>
            <td>
                <el-form-item label="合同金额">
      <el-input v-model="form.addDtos.sCcontractPrice" />
    </el-form-item>
            </td>
            <td>
                <el-form-item label="优惠总额">
      <el-input  v-model="form.addDtos.scPreferentialPrice" @change="aa" />
    </el-form-item>
            </td>
            <td>
                <el-form-item label="优惠后总额">
      <el-input v-model="form.addDtos.preferentialPrice" />
    </el-form-item>
            </td>
            <td>
                <el-form-item label="运杂费">
      <el-input v-model="form.addDtos.sundryPrice" />
    </el-form-item>
            </td>
        </tr>
    </table>
    <table   style="width: 100%">
        <tr>
            <td colspan="4" style="text-align:left">
                <span >收货地址</span>
            </td>
        </tr>
        <tr>
            <td>
                <el-form-item label="收货人">
      <el-input v-model="form.addDtos.scReceivPeople" />
    </el-form-item>
            </td>
            <td>
                <el-form-item label="手机号码">
      <el-input v-model="form.addDtos.scRePhone" />
    </el-form-item>
            </td>
            <td><el-form-item label="省份">
    <el-select v-model="form.addDtos.provinceId" placeholder="请选择省份" style="width: 200px;" @change="getCity(form.addDtos.provinceId)" >
        <el-option label="请选择" :value=0  />
        <el-option v-for="item in Province" :key="item.provinceId" :label="item.provinceName" :value=item.provinceId  />
      </el-select>
  </el-form-item></td>
      <td>  
  <el-form-item label="城市">
    <el-select v-model="form.addDtos.cityId" placeholder="请选择城市" style="width: 200px;">
        <el-option label="请选择" :value=0  />
        <el-option v-for="item in City" :key="item.cityId" :label="item.cityName" :value=item.cityId  />
      </el-select>
  </el-form-item></td>
        </tr>
        <tr>
            <td>
                <el-form-item label="详细地址">
      <el-input v-model="form.addDtos.scAddress" />
    </el-form-item>
            </td>
        </tr>
    </table>
    
     <table   style="width: 100%" >  
        <tr>
            <td style="text-align:left"  >
              
                <div style="height: 50px;">
                    <span >合同明细</span>
            <el-button round @click="addhang()">新增行</el-button>
        </div>
            </td>
            
        </tr>  
      <tr>
        <td  colspan="3">
            <table  :border="1" style="border-collapse: collapse; width: 1000px; height: 40px;">
            <thead>
                <tr>
                    
                    <th style="text-align: center;">序号</th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >产品编号</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >产品名称</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >数量</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >未税单价</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >折扣</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >票据类型</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >明细优惠</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >税额</span> </th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >交货日期</span></th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >备注</span>  </th>
                    <th><span style="height: 40px; width: 100px;text-align: center;" >库存信息</span> </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) in check1" :key="index">
                    <td style=" text-align: center;">{{ index + 1 }}</td>
                   
                    <td>
                        <input v-model="item.pNumber" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   @dblclick="dialogVisible4 = true" placeholder="双击选择产品编号"/>
                    </td>
                    <td>
                        <input v-model="item.pName" type="text"
                            style="height: 40px; width: 100px;text-align: center;" />
                    </td>
                    <td>
                        <input v-model="item.scpNum" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   @change="sumRPNum"  />
                    </td>
                    
                    <td>
                        <input v-model="item.taxPrice" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   />
                    </td>
                    
                    <td>
                        <input v-model="item.discount" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   />
                    </td>
                    
                    <td>
                            <el-select v-model="item.billType" placeholder="请选择" style="width: 100px;">
        <el-option label="不开票" value="不开票" />
        <el-option label="增值税普通发票" value="增值税普通发票" />
        <el-option label="增值税专用质检" value="增值税专用质检" />
      </el-select>
                    </td>
                    <td>
                        <input v-model="item.detailsPreferential" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   />
                           
                    </td>
                    <td>
                        <input v-model="item.taxLines" type="text"
                            style="height: 40px; width: 100px;text-align: center;"  @change="sumRPNums"  />
                            
                    </td>
                    <td>
                        <!-- <input v-model="item.deliveryTime" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   /> -->

                            <el-date-picker
        v-model="item.deliveryTime"
        type="date"
        placeholder="Pick a Date"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />

                    </td>
                    <td>
                        <input v-model="item.sRemark" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   />
                    </td>
                    <td>
                        <input v-model="item.sInventory" type="text"
                            style="height: 40px; width: 100px;text-align: center;"   />
                    </td>

                </tr>
            </tbody>
        </table>
        </td>
        
        
      </tr>
     <tr>
        <td  colspan="2">
            <el-form-item label="数量合计" >
      <el-input v-model="form.addDtos.scNum" style="width: 300px;" />
    </el-form-item>
        </td>
        <td>
            <el-form-item label="税额合计">
      <el-input v-model="form.addDtos.scTax" style="width: 300px;" />
    </el-form-item>
        </td>
     </tr>

     </table>
     <table>
        <tr>
            <td colspan="4" style="text-align:left">
                <span >关联信息</span>
            </td>
        </tr>
        <tr>
            <td>
        <el-form-item label="预生产计划">
            <el-select v-model="form.addDtos.preProductionId" placeholder="请选择" style="width: 300px;">
        
                <el-option label="请选择" :value="0" />
                        <el-option label="不生产预生产计划" :value="1" />
        <el-option label="手动生成预生产计划" :value="2" />
        <el-option label="自动生产预生产计划" :value="3" />
      </el-select>
    </el-form-item>
            </td>
            <td>
    <el-form-item label="关联项目">
      <el-input v-model="form.addDtos.relevancyIName" />
    </el-form-item>
            </td>
        </tr>
     </table>
      
    </table> 
    
    <el-form-item >
      <el-button type="primary" @click="onSubmit">添加</el-button>
    </el-form-item>
 

    
      <el-dialog v-model="dialogVisible3" title="客户名称" width="1000" style="height: 700px;">
        <template #footer>
            <el-row>
<el-col :span="4">
        <el-tree
    style="max-width: 600px"
    :data="Product"
   
    default-expand-all
    
    @node-click="handleNodeClick"
  />


    </el-col>
    <el-col :span="20">
    <el-table :data="Show"    highlight-current-row  @current-change="handleCurrentChange" >
       
    <el-table-column  label="序号" type="index" width="80" />
   
    <el-table-column prop="clientName" label="客户名称"  width="100" />
    <el-table-column prop="provinceName" label="所在省份"  width="100" />
    <el-table-column prop="cityName" label="所在市区"  width="100" />
    <el-table-column prop="cPrimaryContact" label="联系人姓名"  width="100" />
    <el-table-column prop="cPickingStatus" label="领用状态"  width="100" >
        <template #default="scope">
          <span v-if="scope.row.cPickingStatus === 1">未领用</span>
          <span v-if="scope.row.cPickingStatus === 2">待审批</span>
          <span v-if="scope.row.cPickingStatus === 3">已领用</span>
        </template>
    </el-table-column>
    <el-table-column prop="cApplicant" label="申请人员"  width="100" />
    <el-table-column prop="cRecipients" label="领用人员"  width="100" />
    <el-table-column prop="cPickTime" label="领用时间"  width="100" />
    
  </el-table>


    </el-col>
    
</el-row>

<el-button type="primary" @click="dialogVisible3 = false">
                    保存
                </el-button>     
            </template>




      </el-dialog>
      <el-dialog v-model="dialogVisible1" title="我方代表" width="1000" style="height: 700px;">
        <template #footer>
            <el-row>
        <el-col :span="3">
            <el-tree style="max-width: 600px" :data="sectorlist" :props="defaultProps" @node-click="handleNodeClick" />
        </el-col>
        <el-col :span="21">
            <el-table :data="manpowerList" style="width: 100%"   highlight-current-row  @current-change="handleCurrentChange1"  >
                <el-table-column type="index" label="序号" align="center" />
                <el-table-column prop="mNumber" label="档案编号" align="center" />
                <el-table-column prop="mName" label="真实姓名" align="center" />
                <el-table-column prop="users" label="登录账号" align="center" />
                <el-table-column prop="mSex" label="性别" align="center">
                    <template v-slot="scope">
                        {{ scope.row.mSex == 1 ? '男' : '女' }}
                    </template>
                </el-table-column>
                <el-table-column prop="mPhone" label="联系电话" align="center" />
                <el-table-column prop="mBirthDay" label="出生日期" align="center">
                    <template v-slot="scope">
                        {{ scope.row.mBirthDay.substring(0, 10) }}
                    </template>
                </el-table-column>
                <el-table-column prop="sectorName" label="所在部门" align="center" />
                <el-table-column prop="postName" label="所在岗位" align="center" />
            </el-table>
        </el-col>
    </el-row>


<el-button type="primary" @click="dialogVisible1 = false">
                    保存
                </el-button>     
            </template>





      </el-dialog>
      <el-dialog v-model="dialogVisible2" title="对方代表" width="1000" style="height: 700px;">
        <template #footer>
            <el-row>
<el-col :span="4">
        <el-tree
    style="max-width: 600px"
    :data="Product"
    default-expand-all
  />


    </el-col>
    <el-col :span="20">
    <el-table :data="Show"    highlight-current-row  @current-change="handleCurrentChange" >
       
    <el-table-column  label="序号" type="index" width="80" />
  
    <el-table-column prop="clientName" label="客户名称"  width="100" />
    <el-table-column prop="provinceName" label="所在省份"  width="100" />
    <el-table-column prop="cityName" label="所在市区"  width="100" />
    <el-table-column prop="cPrimaryContact" label="联系人姓名"  width="100" />
    <el-table-column prop="cPickingStatus" label="领用状态"  width="100" >
        <template #default="scope">
          <span v-if="scope.row.cPickingStatus === 1">未领用</span>
          <span v-if="scope.row.cPickingStatus === 2">待审批</span>
          <span v-if="scope.row.cPickingStatus === 3">已领用</span>
        </template>
    </el-table-column>
    <el-table-column prop="cApplicant" label="申请人员"  width="100" />
    <el-table-column prop="cRecipients" label="领用人员"  width="100" />
    <el-table-column prop="cPickTime" label="领用时间"  width="100" />
   
  </el-table>


    </el-col>
    
</el-row>

<el-button type="primary" @click="dialogVisible2 = false">
                    保存
                </el-button>     
            </template>

      </el-dialog>
      <el-dialog v-model="dialogVisible4" title="产品名称选择" width="1000" style="height: 700px;"
            :before-close="handleClose">
            <span></span>
            <template #footer>
                <el-row>
                    <el-col :span="4">
                        <el-tree style="max-width: 600px" :data="VendorType" :props="defaultProps"
                            default-expand-all="true" />
                    </el-col>
                    <el-col :span="20">
                        <el-table :data="tableData" border style="width: 100%"
                        highlight-current-row @selection-change="handleSelectionChange3">
                         <el-table-column type="selection" width="55" />
                            <el-table-column prop="pName" label="产品名称" align="center" />
                            <el-table-column prop="pNumber" label="产品编号" align="center" />
                            <el-table-column prop="pUnit" label="规格型号" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
                <el-button type="primary" @click="dialogVisible4 = false">
                    保存
                </el-button>
            </template>
        </el-dialog>
</el-form>


</template>
<script setup lang="ts">
import http from '../../../http.js'
import {ref,onMounted,reactive} from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute} from 'vue-router'
const router = useRouter()
const route = useRoute()
const ruleFormRef = ref<FormInstance>();
onMounted(()=>{
    form.addDtos.sCcontractNumber='XSHT' + Math.floor(1000 + Math.random() * 9000);
    ProductType();
    GetShow();
    GetManpowerList();
    GetSectorList();
    getProvince();
    getVendorType();
    ProductList();
    
})
const form=reactive({

    CIndustry:'',
    addDtos: {
  saleContractId:route.query.id,
    clientId: 0,
    clientName: "",
    scAgencyDate: "",
    contractTopic: "",
    sCcontractNumber: "",
    scStartDate: "",
    scEndDate: "",
    scPeople: "",
    scCountpartPeople: "",
    scContractType: "",
    scSalespeopleId: 0,
    scSalespeople: "",
    documentMakers: "",
    documentTime: "",
    sCcontractPrice: '',
    scPreferentialPrice: '',
    preferentialPrice:'',
    sundryPrice: '',
    scReceivPeople: "",
    scRePhone: "",
    provinceId: 0,
    cityId: 0,
    scAddress: "",
    scNum: 0,
    scTax: 0,
    preProductionId: 0,
    relevancyIName:'',
    saleContractProductDto: [
      {
        saleContractProductId:'',
        sCcontractNumber: '',
        productId: 0,
        pName: "",
        pNumber: "",
        scpNum: 0,
        taxPrice: 0,
        discount: 0,
        billType: "",
        detailsPreferential: "",
        taxLines: 0,
        deliveryTime: "",
        sRemark: "",
        sInventory: ""
      }
    ]
  }

})

//#region 仨弹出层 

const dialogVisible3 = ref(false)//双击产品名称弹出层
const dialogVisible1 = ref(false)//双击我方代表弹出层
const dialogVisible2 = ref(false)//双击对方代表弹出层
//单选
const currentRow = ref()
const handleCurrentChange = (val: User | undefined) => {
  currentRow.value = val
  console.log(currentRow.value)
  form.addDtos.clientName=currentRow.value.clientName
  form.addDtos.clientId=currentRow.value.clientId
  form.addDtos.scCountpartPeople=currentRow.value.cPrimaryContact
}

var Product=ref([]);
const ProductType=()=>{
    axios.get(http.zblnb + '/vendor/api/Client/ProductTypeSelect').then(res=>{
        Product.value=res.data.data
        console.log(res.data.data)
    })
}
var Show=ref([]);
const GetShow=()=>{
    axios.get(http.zblnb + '/vendor/api/Client/ClientAllShow',{
        params:{
    pageIndex:1,
    pageSize:15,
    CIndustry: form.CIndustry,
        }
    }).then(res=>{
         Show.value=res.data.data.list
    })
}
const defaultProps = {
    children: 'children',
    label: 'label',
}


const handleNodeClick = (data: Tree) => {
  console.log(data.value)
  form.CIndustry=data.value
  GetShow();
}

//显示人员档案
const manpowerList = ref([])
const GetManpowerList = () => {
    axios.get(http.zblnb + '/vendor/api/Manpower/GetManpowerList', {
        params: {
            Pindex: 1,
            Psize:100,
           
        }
    })
        .then(res => {
            manpowerList.value = res.data.data.list
            
        })
}
//部门
const sectorlist = ref([])
const GetSectorList = () => {
    axios.get(http.zblnb + '/vendor/api/Post/GetSectorList')
        .then(res => {
            sectorlist.value = res.data.data;
        })
}
const handleCurrentChange1 = (val: any | undefined) => {
  currentRow.value = val
  console.log(currentRow.value)
  form.addDtos.scPeople=currentRow.value.mName
}
//#endregion

//#region 省市
//省份
var Province=ref([]);
const getProvince = () => {
    axios.get(http.zblnb+'/cg/api/Vendor/ProvinceSelect').then(res=>{
    if(res.data.code==200){
        Province.value=res.data.data
    }
    console.log(Province.value)
})
}
//城市
var City=ref([]);
const getCity = (id:number) => {
    axios.get(http.zblnb+'/cg/api/Vendor/CitySelect?ProvinceId='+id).then(res=>{
    if(res.data.code==200){
        City.value=res.data.data
    }
    console.log(City.value)
});
}

//#endregion
//#region 表格
//点击新增行
const addhang = () => {
    check1.value.push({
        saleContractProductId: 0,
        sCcontractNumber: "",
        productId: 0,
        pName: "",
        pNumber: "",
        scpNum: 0,
        taxPrice: 0,
        discount: 0,
        billType: "",
        detailsPreferential: "",
        taxLines: 0,
        deliveryTime: "",
        sRemark: "",
        sInventory: "",
  
    });
}
const dialogVisible4 = ref(false)//双击产品名称弹出层
var VendorType = ref([]);
const getVendorType = () => {
    axios.get(http.zblnb+'/cg/api/Vendor/ProductTypeSelect').then(res => {
        if (res.data.code == 0) {
            VendorType.value = res.data.data
        }
        console.log(VendorType.value)
    })
}
const check1 = ref([])
const handleSelectionChange3 = (val: any) => {  
    check1.value = val;  
    console.log(check1.value);  
}; 
//获取产品列表
const tableData=ref([])
const ProductList = () => {
    axios.get(http.zblnb+'/erpcp/api/Product/ProductShow', {
        params: {
            PageIndex:1,
            PageSize: 10,

        }
    })
    .then(res => {
        // console.log(res)
        tableData.value = res.data.data.list
    })
    .catch(err => {
        console.log(err)    
    })
}
//#endregion


const onSubmit=()=>{
  // 清空现有的子件（如有必要）  
  form.addDtos.saleContractProductDto = [];  
//  form.addDtos.preferentialPrice=form.addDtos.sCcontractPrice-form.addDtos.scPreferentialPrice
check1.value.forEach(item => {  
   
    const newItem = {  
        sCcontractNumber:form.addDtos.sCcontractNumber,
        productId: item.productId,
        pName: item.pName,
        pNumber: item.pNumber,
        scpNum: item.scpNum,
        taxPrice: item.taxPrice,
        discount: item.discount,
        billType: item.billType,
        detailsPreferential: item.detailsPreferential,
        taxLines: item.taxLines,
        deliveryTime: item.deliveryTime,
        sRemark: item.sRemark,
        sInventory: item.sInventory
    };  

    console.log(newItem); // 调试步骤  
    if (newItem.productId != 0) {  
        form.addDtos.saleContractProductDto.push(newItem);  
    }  

});  
console.log(form.addDtos)
console.log()

axios.post(http.zblnb + '/cw/api/SaleContract/AddStateSalesReturn', {
        addDtos:form.addDtos
    }).then(response => {
   
    console.log(response.data)
    if(response.data.code==200)
    {
        ElMessage({
            message: '添加成功',
            type: 'success',
            
        })
        router.push('SaleContractShow')
    }
    else
    {
        ElMessage({
            message: '添加失败',
            type: 'error',
        })
    }


})

    console.log(form.addDtos)
}


const aa=()=>{
    form.addDtos.preferentialPrice= form.addDtos.sCcontractPrice-form.addDtos.scPreferentialPrice
}
//输入数量change事件
const sumRPNum = (sum: number) => {
    console.log(sum)
    form.addDtos.scNum += Number(sum.srcElement.__vnode.dirs[0].value);
    console.log( form.addDtos.scNum)
}

//输入数量change事件
const sumRPNums = (sum: number) => {
    console.log(sum)
    form.addDtos.scTax += Number(sum.srcElement.__vnode.dirs[0].value);
    console.log( form.addDtos.scTax)
}

</script>